package com.usher.greendao_demo.greendao.gen.greendao;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;


import com.usher.greendao_demo.greendao.gen.DaoMaster;
import com.usher.greendao_demo.greendao.gen.DaoSession;
import com.usher.greendao_demo.greendao.gen.GoodsUserDao;

import org.greenrobot.greendao.database.Database;

/**
 * Created by wanggang on 2017/1/19.
 */

public class GreenDaoUtils {

   private DaoSession session;

    private static GreenDaoUtils instance;

    private GreenDaoUtils(Context context){
        //SQLiteOpenHelper
        //myDb  数据库名字
        DaoMaster.DevOpenHelper helper=new
                MyHelper(context,"myDb");
        //加密的Database   key
        Database db = helper.getWritableDb();
        DaoMaster master=new DaoMaster(db);
        session = master.newSession();
    }


    public static GreenDaoUtils getInstance(Context context){
        if(instance==null){
            synchronized (GreenDaoUtils.class){
                if(instance==null){
                    instance=new GreenDaoUtils(context);
                }
            }
        }
        return instance;
    }


    public GoodsUserDao getUserDao(){
        return session.getGoodsUserDao();
    }



    public static class MyHelper extends DaoMaster.DevOpenHelper{

        public MyHelper(Context context, String name) {
            super(context, name);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            super.onUpgrade(db, oldVersion, newVersion);
            //数据
            //数据迁移
            MigrationHelper.migrate(db,GoodsUserDao.class);
        }

        @Override
        public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            super.onDowngrade(db, oldVersion, newVersion);
        }
    }
}
